import {
  Injectable,
  NotFoundException,
  ForbiddenException,
  BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, IsNull } from 'typeorm';
import { Comment } from './entities/comment.entity';
import { Work } from '../works/entities/work.entity';
import { User } from '../auth/entities/user.entity';
import { CreateCommentDto } from './dto/create-comment.dto';

@Injectable()
export class CommentsService {
  constructor(
    @InjectRepository(Comment)
    private readonly commentRepository: Repository<Comment>,
    @InjectRepository(Work)
    private readonly workRepository: Repository<Work>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  /**
   * 创建评论（支持一级和二级评论）
   */
  async create(
    createCommentDto: CreateCommentDto,
    userId: number,
  ): Promise<Comment> {
    const { workId, content, parentId, replyToUserId } = createCommentDto;

    // 验证作品是否存在
    const work = await this.workRepository.findOne({ where: { id: workId } });
    if (!work) {
      throw new NotFoundException('作品不存在');
    }

    // 如果是二级评论，验证父评论
    if (parentId) {
      const parentComment = await this.commentRepository.findOne({
        where: { id: parentId },
      });
      if (!parentComment) {
        throw new NotFoundException('父评论不存在');
      }
      // 只支持两级评论，不支持三级
      if (parentComment.parentId) {
        throw new BadRequestException('不支持三级评论，请回复一级评论');
      }
    }

    // 验证回复的用户是否存在
    if (replyToUserId) {
      const replyToUser = await this.userRepository.findOne({
        where: { id: replyToUserId },
      });
      if (!replyToUser) {
        throw new NotFoundException('回复的用户不存在');
      }
    }

    // 创建评论
    const comment = this.commentRepository.create({
      workId,
      userId,
      content,
      parentId: parentId || null,
      replyToUserId: replyToUserId || null,
    });

    const savedComment = await this.commentRepository.save(comment);

    // 更新作品评论数
    await this.workRepository.increment({ id: workId }, 'commentsCount', 1);

    // 如果是二级评论，更新父评论的回复数
    if (parentId) {
      await this.commentRepository.increment(
        { id: parentId },
        'repliesCount',
        1,
      );
    }

    // 返回包含用户信息的评论
    const commentWithRelations = await this.commentRepository.findOne({
      where: { id: savedComment.id },
      relations: ['user', 'replyToUser'],
    });

    return commentWithRelations!;
  }

  /**
   * 获取作品的评论列表（分页，仅一级评论）
   */
  async findByWork(
    workId: number,
    page: number = 1,
    limit: number = 20,
  ): Promise<{
    data: Comment[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  }> {
    const [comments, total] = await this.commentRepository.findAndCount({
      where: {
        workId,
        parentId: IsNull(), // 只获取一级评论
        isDeleted: false,
      },
      relations: ['user'],
      order: {
        createdAt: 'DESC', // 最新的在前
      },
      skip: (page - 1) * limit,
      take: limit,
    });

    return {
      data: comments,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  /**
   * 获取评论的回复列表（二级评论）
   */
  async findReplies(
    parentId: number,
    page: number = 1,
    limit: number = 10,
  ): Promise<{
    data: Comment[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  }> {
    const [replies, total] = await this.commentRepository.findAndCount({
      where: {
        parentId,
        isDeleted: false,
      },
      relations: ['user', 'replyToUser'],
      order: {
        createdAt: 'ASC', // 早的在前（更符合对话逻辑）
      },
      skip: (page - 1) * limit,
      take: limit,
    });

    return {
      data: replies,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  /**
   * 获取用户的评论列表
   */
  async findByUser(
    userId: number,
    page: number = 1,
    limit: number = 20,
  ): Promise<{
    data: Comment[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  }> {
    const [comments, total] = await this.commentRepository.findAndCount({
      where: {
        userId,
        isDeleted: false,
      },
      relations: ['work', 'user'],
      order: {
        createdAt: 'DESC',
      },
      skip: (page - 1) * limit,
      take: limit,
    });

    return {
      data: comments,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  /**
   * 删除评论（软删除）
   * 只有评论作者或作品作者可以删除
   */
  async remove(commentId: number, userId: number): Promise<void> {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId },
      relations: ['work'],
    });

    if (!comment) {
      throw new NotFoundException('评论不存在');
    }

    // 检查权限：评论作者或作品作者可以删除
    if (comment.userId !== userId && comment.work.authorId !== userId) {
      throw new ForbiddenException('无权删除此评论');
    }

    // 软删除
    comment.isDeleted = true;
    await this.commentRepository.save(comment);

    // 减少作品评论数
    await this.workRepository.decrement(
      { id: comment.workId },
      'commentsCount',
      1,
    );

    // 如果是二级评论，减少父评论的回复数
    if (comment.parentId) {
      await this.commentRepository.decrement(
        { id: comment.parentId },
        'repliesCount',
        1,
      );
    }
  }

  /**
   * 点赞评论
   * TODO: 后续需要创建 comment_likes 表来记录点赞
   */
  async like(commentId: number, userId: number): Promise<void> {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId },
    });

    if (!comment) {
      throw new NotFoundException('评论不存在');
    }

    // TODO: 检查是否已点赞
    // const existingLike = await this.commentLikeRepository.findOne({ where: { commentId, userId } });

    await this.commentRepository.increment({ id: commentId }, 'likesCount', 1);
  }

  /**
   * 取消点赞评论
   */
  async unlike(commentId: number, userId: number): Promise<void> {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId },
    });

    if (!comment) {
      throw new NotFoundException('评论不存在');
    }

    // TODO: 检查点赞记录
    // const likeRecord = await this.commentLikeRepository.findOne({ where: { commentId, userId } });

    await this.commentRepository.decrement({ id: commentId }, 'likesCount', 1);
  }
}
